package com.cs.base;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.viewbinding.ViewBinding;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.cs.base.dialog.LoadingDialog;
import com.cs.base.manage.AppManager;
import com.cs.base.permission.RxPermissions;
import com.cs.base.util.NetStateUtil;
import com.cs.base.vm.BaseViewModel;
import com.githang.statusbar.StatusBarCompat;


/**
 * 文件名: BaseActivity
 */

public abstract class BaseActivity<VM extends BaseViewModel, VB extends ViewBinding> extends AppCompatActivity
        implements View.OnClickListener{
    protected static String TAG;

    protected Context context;
    protected VM viewModel;
    //ViewBinding
    protected VB binding;
    //加载框
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();
        context = this;
        // 把Activity放到application栈中管理
        AppManager.getAppManager().addActivity(this);
        //设置状态栏为白色
        setStatusBarNormal();
        //初始化ViewDataBinding，设置ContentView
        binding = getViewBinding();
        //设置布局
        setContentView(binding.getRoot());
        //初始化ViewModel
        viewModel = initViewModel();
        //初始化监听
        initObserve();
        //初始化view
        initView();
        //初始化数据
        initData();
    }

    /**
     * 设置白色状态栏
     */
    public void setStatusBarNormal() {
        StatusBarCompat.setStatusBarColor(this, Color.WHITE);
    }

    /**
     * 初始化要加载的布局资源ID, 获取子类布局ViewBinding
     * 此函数优先执行于onCreate()可以做window操作
     */
    protected abstract VB getViewBinding();

    /**
     * 初始化ViewModel
     */
    protected  VM initViewModel(){
        return null;
    };

    /**
     * 监听当前ViewModel中 showDialog和error的值
     */
    private void initObserve() {
        if (viewModel == null) {
            return;
        }
        viewModel.setDialogObserver(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean isShow) {
                if (isShow) {
                    showLoading();
                } else {
                    dismissLoading();
                }
            }
        });
        viewModel.setErrorObserver(this, new Observer<Object>() {
            @Override
            public void onChanged(Object obj) {
                showError(obj);
            }
        });
    }

    /**
     * 初始化视图
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 申请权限
     * @param permissions Manifest.permission.WRITE_EXTERNAL_STORAGE
     */
    protected void requestPermissions(int request,final String... permissions){
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(permissions)
                .subscribe(granted -> {
                    onPermissions(request,granted,permissions);
                });
    }

    /**
     * 处理权限申请结果
     */
    protected void onPermissions(int request,boolean granted,final String... permissions){
        LogUtils.d(TAG,"request="+request,"granted="+granted,"permissions="+permissions);
    }

    @Override
    public void onClick(View v) {}

    /**
     * @param path 路由
     * @return
     */
    protected static Postcard router(String path){
        //跳转并携带参数 /demo/ModuleActivity  获取参数getIntent()
        return ARouter.getInstance().build(path);
                /*.withLong("key1", 666L)
                .withString("key3", "888")
                .navigation();*/
    }

    /**
     * 显示加载框
     */
    protected void showLoading() {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(context);
            loadingDialog.show();
        }else if(!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    /**
     * 隐藏等待框
     */
    protected void dismissLoading() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
            loadingDialog = null;
        }
    }

    /**
     * 设置加载框提示
     * @param msg
     */
    protected void setLoadingMsg(String msg){
        if(loadingDialog != null){
            loadingDialog.setLoadingMsg(msg);
        }
    }

    /**
     * ViewModel层发生了错误
     */
    protected void showError(Object obj) {}

    /**
     * 检查网络状态
     * @return
     */
    public boolean checkNetWork() {
        return NetStateUtil.isNetworkAvailable(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
        AppManager.getAppManager().finishActivity(this);
    }
}
